﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace Movistar.SMS.VSTOInstaller
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            string[] args = Environment.GetCommandLineArgs();

            if (args.Count() != 3)
                MessageBox.Show("Argumentos inválidos. VSTOInstaller [/I|/U] <uri>", "Movistar SMS VSTO Installer", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

            if ((args[1].ToUpper() == "/I") || (args[1].ToUpper() == "/U"))
            {
                int returnCode = ExecuteVSTOInstaller(String.Format("{0} {1}", args[1], args[2]));

                if(returnCode!=0)
                    MessageBox.Show("Error invocando VSTOInstaller. Error Code "+returnCode.ToString(), 
                        "Movistar SMS VSTO Installer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
                MessageBox.Show("Argumentos inválidos. VSTOInstaller [/I|/U] <uri>.", "Movistar SMS VSTO Installer", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
        }

        static int ExecuteVSTOInstaller(string arguments)
        {
            string basePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles);

            string subPath = @"Microsoft Shared\VSTO\9.0\VSTOInstaller.exe";

            string vstoInstallerPath = Path.Combine(basePath, subPath);

            if (File.Exists(vstoInstallerPath) == false)
            {
                MessageBox.Show("El instalador de Visual Studio Tools for Office no se ha encontrado.", "Movistar SMS VSTO Installer", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }

            ProcessStartInfo startInfo = new ProcessStartInfo(vstoInstallerPath);

            startInfo.Arguments = arguments;
            startInfo.WorkingDirectory = basePath;
            Process process = Process.Start(startInfo);

            process.WaitForExit();

            return process.ExitCode;
        }
    }
}
